#include "logreg.h"
#include "ui_logreg.h"
#include <QPixmap>
#include <QPalette>
LogReg::LogReg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LogReg)
{
    ui->setupUi(this);
    log_flag =false;
    this->setWindowTitle("登录注册");
    QPixmap pixmap = QPixmap(":/img/bg1.jpg");
    QPixmap pix = pixmap.scaled(this->size());
    QPalette pal;
    pal.setBrush(QPalette::Background,QBrush(pix));
    this->setPalette(pal);
    db = Database::getInstance().getDatabase();
    reg = new Reg();
    connect(reg,&Reg::show_main,[=](){reg->close();this->show();});
}

LogReg::~LogReg()
{
    delete ui;
}

bool LogReg::get_log_flag()
{
    return log_flag;
}

void LogReg::on_pushButton_log_clicked()
{
    QString username = ui->lineEdit_name->text();
    QString password = ui->lineEdit_pwd->text();

    QByteArray hash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256);
    QString hashedPassword = hash.toHex();

    QSqlQuery query(db);
    query.prepare("SELECT id FROM users WHERE username = ? AND password = ?");
    query.addBindValue(username);
    query.addBindValue(hashedPassword);

    if (query.exec() && query.next()) {
        int userId = query.value(0).toInt();
        QMessageBox::information(this, "Success", "Login successful! User ID: " + QString::number(userId));
        log_flag = true;
        this->close();
        emit show_main();

    } else {
        QMessageBox::critical(this, "Error", "Invalid credentials");
    }
}

void LogReg::on_pushButton_reg_clicked()
{
    this->close();
    reg->show();
}

void LogReg::on_checkBox_stateChanged(int arg1)
{
    if(ui->checkBox->isChecked())
        ui->lineEdit_pwd->setEchoMode(QLineEdit::Normal);
    else
        ui->lineEdit_pwd->setEchoMode(QLineEdit::Password);
}
